"use strict";
var _iconvLite = _interopRequireDefault(require("iconv-lite"));
var _urlencode = _interopRequireDefault(require("urlencode"));
var _novelRequest = _interopRequireDefault(require("./novel-request"));
var _quert = require("../../utils/quert");
function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
_iconvLite.default.skipDecodeWarning = true;
let BaseParser = class BaseParser {
    async getPageContent(url, { useCache =true , headers ={} , timeout =5000  } = {}) {
        const res = await _novelRequest.default.push({
            url,
            method: 'get',
            timeout,
            headers
        }, useCache);
        return _iconvLite.default.decode(res, this.config.charset);
    }
    async getPostContent({ url , timeout =5000 , headers  }) {
        const [newUrl, qstring] = url.split('?');
        const res = await _novelRequest.default.push({
            method: 'post',
            headers,
            url: newUrl,
            data: qstring,
            timeout
        }, true);
        return _iconvLite.default.decode(res, this.config.charset);
    }
    async getChapterList(url) {
        const { list  } = this.config;
        const content = await this.getPageContent(url);
        const chapters = (0, _quert).htmlAnalysis(content, list.chapters);
        const novelList = [];
        const hrefSet = new Set();
        for(let i = chapters.length - 1; i >= 0; i--){
            const item = chapters[i];
            const title = (0, _quert).htmlAnalysis(item, list.title);
            const href = (0, _quert).htmlAnalysis(item, list.href);
            if (title.length < 1 || href == null) {
                continue;
            }
            const curHref = new URL(href, url).toString().replace(/(.*)(\/.*\/){2}(.*)/, '$1$2$3');
            if (!hrefSet.has(curHref)) {
                novelList.push({
                    title,
                    url: curHref
                });
                hrefSet.add(curHref);
            }
        }
        hrefSet.clear();
        return novelList.reverse();
    }
    async getLatestChapter(url) {
        const res = await this.getPageContent(url);
        return (0, _quert).htmlAnalysis(res, this.config.detail.latest);
    }
    async getChapterDetail(url) {
        let res = await this.getPageContent(url);
        res = res.replace(/&nbsp;/g, '').replace(/<br>/g, '${line}').replace(/<br \/>/g, '${line}').replace(/<br\/>/g, '${line}');
        const { chapter  } = this.config;
        const base = (0, _quert).htmlAnalysis(res);
        const asContent = (0, _quert).htmlAnalysis(base, chapter.content);
        const text = asContent.replace(/\${line}/g, '\n').replace(/[ ]+/g, '').replace(/[　]+/g, '').replace(/\n+/g, '\n').replace(/\t+/g, '');
        const ret = {
            title: (0, _quert).htmlAnalysis(base, chapter.title),
            content: text,
            prevUrl: '',
            nextUrl: ''
        };
        if (chapter.nextUrl) {
            const asPrevHref = (0, _quert).htmlAnalysis(base, chapter.prevUrl);
            const asNextHref = (0, _quert).htmlAnalysis(base, chapter.nextUrl);
            ret.prevUrl = asPrevHref ? new URL(asPrevHref, url).toString() : '';
            ret.nextUrl = asNextHref ? new URL(asNextHref, url).toString() : '';
        }
        return ret;
    }
    get canSearch() {
        return this.config.search != null;
    }
    async search(keyword) {
        const { search , charset  } = this.config;
        const { pattern , method , closeEncode , customHeader  } = search;
        const preHeader = customHeader ? JSON.parse(customHeader) : {};
        const searchUrl = pattern.replace('${key}', _urlencode.default.encode(keyword, closeEncode ? 'utf-8' : charset));
        let res;
        if (method === 'post') {
            res = await this.getPostContent({
                url: searchUrl,
                headers: preHeader
            });
        } else {
            res = await this.getPageContent(searchUrl);
        }
        // TODO: 可以考虑兼容一下特定搜索词直接进入指定书籍页面，没走列表的场景（看看目标的url是否符合书籍规则）
        const searchList = [];
        const list = (0, _quert).htmlAnalysis(res, search.bookList);
        for(let i = 0; i < list.length; i++){
            const item = list[i];
            const name = (0, _quert).htmlAnalysis(item, search.bookName);
            const author = (0, _quert).htmlAnalysis(item, search.author);
            const href = (0, _quert).htmlAnalysis(item, search.bookUrl);
            if (href == null || name.length < 1) {
                continue;
            }
            const payload = {
                bookName: name,
                bookUrl: new URL(href, searchUrl).toString(),
                author,
                latestChapter: undefined
            };
            if (search.latestChapter !== '') {
                payload.latestChapter = (0, _quert).htmlAnalysis(item, search.latestChapter);
            }
            searchList.push(payload);
        }
        return searchList;
    }
    /** 获取书籍详情 */ async getBookDetail(url) {
        const { latest , description , imageUrl , catalogUrl , author , name  } = this.config.detail;
        const res = await this.getPageContent(url);
        const base = (0, _quert).htmlAnalysis(res);
        const payload = {
            latest: (0, _quert).htmlAnalysis(base, latest),
            desc: (0, _quert).htmlAnalysis(base, description).trim(),
            name: (0, _quert).htmlAnalysis(base, name),
            author: (0, _quert).htmlAnalysis(base, author),
            image: new URL((0, _quert).htmlAnalysis(base, imageUrl), this.config.site).toString(),
            url,
            catalogUrl: url
        };
        if (catalogUrl != null && catalogUrl !== '') {
            payload.catalogUrl = new URL((0, _quert).htmlAnalysis(base, catalogUrl), this.config.site).toString();
        }
        return payload;
    }
    constructor(config){
        this.config = config;
        if (!this.config) {
            throw Error('unsupported site');
        }
    }
};
module.exports = BaseParser;
